/*
 * atmega_adc.c
 *
 * Created: 4/4/2011 17:03:26
 *  Author: morpheus
 */ 
void InitADC() 
{ 
  ADMUX=(1<<REFS0); 
  // For Aref=AVcc; 
  ADCSRA=(1<<ADEN)|(1<<ADPS2)|(1<<ADPS1)|(1<<ADPS0); 
  //Rrescalar div factor =128 
} 

uint16_t ReadADC(uint8_t ch) 
{ 

  //Select ADC Channel ch must be 0-7, in case some other components 
  //will be added to the system that require ADC 
  ch=ch&0b00000111; 
  ADMUX&=0b11100000; 
  ADMUX|=ch; 

  //Start Single conversion 
  ADCSRA|=(1<<ADSC); 

  //Wait for conversion to complete 

  while(!(ADCSRA & (1<<ADIF))); 

  //Clear ADIF by writing one to it 
  ADCSRA|=(1<<ADIF); 

  return(ADC); 
} 

void Wait() 
{ 
  uint8_t i; 
  for(i=0;i<10;i++) 
   _delay_loop_2(0); 
} 


int main() 
{ 
  
  uint16_t adc_result[4]; 
  //Array to store the adc values one each of the analogue pins

  float distance = 0;    
  // Variable to save the distance calculated after ADC on pin0

  //Initialize ADC 
  InitADC(); 
  Wait(); // Create a delay  

  while(1) 
  { 
    adc_result[0]=ReadADC(0);    
    // Read Analog value from channel-0: distance 
    distance =  (adc_result[0] * 2.54) / 9.7656; 
    // Calculate distance 
  } 
}

